# -*- coding: utf-8 -*-
"""
快速测试脚本 - 测试 LLM 服务的基础功能

@author: AI Assistant
"""
import sys
from pathlib import Path

# 添加项目路径
project_root = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(project_root))

from loguru import logger


def test_imports():
    """测试所有模块是否能正常导入"""
    logger.info("测试模块导入...")
    
    try:
        from config import OLLAMA_CONFIG, SERVICE_CONFIG
        logger.info("  ✅ config 导入成功")
        
        from models import SessionQueryRequest, ChatRequest, ChatResponse
        logger.info("  ✅ models 导入成功")
        
        from services import SessionService, LLMService, ParameterService, ConversationManager
        logger.info("  ✅ services 导入成功")
        
        from utils import PromptTemplateGenerator
        logger.info("  ✅ utils 导入成功")
        
        from api.routes import router
        logger.info("  ✅ api 导入成功")
        
        return True
    except Exception as e:
        logger.error(f"  ❌ 导入失败: {e}")
        return False


def test_config():
    """测试配置是否正确"""
    logger.info("测试配置...")
    
    try:
        from config import OLLAMA_CONFIG, SERVICE_CONFIG, CONVERSATION_STORAGE_PATH
        
        logger.info(f"  - Ollama地址: {OLLAMA_CONFIG['base_url']}")
        logger.info(f"  - 模型: {OLLAMA_CONFIG['chat_model']}")
        logger.info(f"  - 服务端口: {SERVICE_CONFIG['port']}")
        logger.info(f"  - 存储路径: {CONVERSATION_STORAGE_PATH}")
        logger.info("  ✅ 配置加载成功")
        return True
    except Exception as e:
        logger.error(f"  ❌ 配置加载失败: {e}")
        return False


def test_database_connection():
    """测试数据库连接（只读模式）"""
    logger.info("测试数据库连接...")
    
    try:
        from utils.postgres_util import get_postgres_data
        
        conn = get_postgres_data()
        logger.info("  ✅ 数据库连接成功（只读模式）")
        conn.close()
        return True
    except Exception as e:
        logger.error(f"  ❌ 数据库连接失败: {e}")
        return False


def test_llm_connection():
    """测试 LLM 连接"""
    logger.info("测试 LLM 连接...")
    
    try:
        from services import LLMService
        
        llm_service = LLMService()
        if llm_service.test_connection():
            logger.info("  ✅ LLM 连接成功")
            return True
        else:
            logger.warning("  ⚠️  LLM 连接测试未通过")
            return False
    except Exception as e:
        logger.error(f"  ❌ LLM 连接失败: {e}")
        return False


def main():
    """运行所有测试"""
    logger.info("=" * 60)
    logger.info("LLM 服务快速测试")
    logger.info("=" * 60)
    
    results = {
        "导入测试": test_imports(),
        "配置测试": test_config(),
        "数据库连接": test_database_connection(),
        "LLM连接": test_llm_connection()
    }
    
    logger.info("\n" + "=" * 60)
    logger.info("测试结果汇总")
    logger.info("=" * 60)
    
    for test_name, result in results.items():
        status = "✅ 通过" if result else "❌ 失败"
        logger.info(f"  {test_name}: {status}")
    
    total = len(results)
    passed = sum(results.values())
    
    logger.info(f"\n总计: {passed}/{total} 测试通过")
    
    if passed == total:
        logger.info("\n🎉 所有测试通过！服务可以正常启动。")
        logger.info("\n启动命令: python main.py")
    else:
        logger.warning("\n⚠️  部分测试失败，请检查配置和依赖。")
    
    return passed == total


if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)

